import os
import sys

from common import get_ffmpeg_path
from log_manager import LogManager


def get_whisper_assets_path():
    """获取 whisper 资源文件路径"""
    if getattr(sys, "frozen", False):
        # 如果是打包后的应用
        base_path = os.path.dirname(sys.executable)
        if sys.platform == "darwin":
            # macOS
            base_path = os.path.dirname(os.path.dirname(os.path.dirname(base_path)))
            assets_path = os.path.join(base_path, "Resources", "whisper", "assets")
        else:
            # Windows
            assets_path = os.path.join(base_path, "whisper", "assets")
    else:
        # 开发环境
        import whisper

        assets_path = os.path.join(os.path.dirname(whisper.__file__), "assets")
    return assets_path


def get_whisper_model_path(model_name="medium"):
    """获取 whisper 模型文件路径"""
    if getattr(sys, "frozen", False):
        # 如果是打包后的应用
        base_path = os.path.dirname(sys.executable)
        if sys.platform == "darwin":
            # macOS
            base_path = os.path.dirname(os.path.dirname(os.path.dirname(base_path)))
            model_path = os.path.join(
                base_path, "Resources", "whisper", "models", f"{model_name}.pt"
            )
        else:
            # Windows
            model_path = os.path.join(
                base_path, "whisper", "models", f"{model_name}.pt"
            )
    else:
        # 开发环境
        model_path = os.path.expanduser(f"~/.cache/whisper/{model_name}.pt")
    return model_path


def has_char_in_str(str, chars):
    for char in chars:
        if char in str:
            return True
    return False


def call_whisper_api(
    video_path, model_name="medium"
):
    """
    使用 Whisper 模型识别视频中的语音，并生成 SRT 字幕文件

    Args:
        video_path: 视频文件路径
        output_path: 输出的 SRT 文件路径
    """
    # 设置 whisper 资源文件路径
    import whisper
    import whisper.audio

    whisper.ASSETS_PATH = get_whisper_assets_path()

    # 设置模型文件路径
    model_path = get_whisper_model_path(model_name)
    if not os.path.exists(model_path):
        LogManager.log(f"正在下载模型文件:{model_name}")
        model = whisper.load_model(model_name)
    else:
        LogManager.log(f"使用本地模型文件:{model_path}")
        model = whisper.load_model(model_path)

    original_load_audio = whisper.audio.load_audio

    def patched_load_audio(file: str, sr: int = 16000):
        """补丁函数，使用正确的 ffmpeg 路径"""
        import subprocess

        import numpy as np

        cmd = [
            get_ffmpeg_path(),
            "-nostdin",
            "-threads",
            "0",
            "-i",
            file,
            "-f",
            "s16le",
            "-ac",
            "1",
            "-acodec",
            "pcm_s16le",
            "-ar",
            str(sr),
            "-",
        ]
        try:
            out = subprocess.run(cmd, capture_output=True, check=True).stdout
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e

        return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0

    # 替换原始函数
    whisper.audio.load_audio = patched_load_audio

    try:
        ref_text = None
        if ref_text:
            initial_prompt = (
                "Please output subtitles in simplified Simplified Chinese according to"
                " the original text. Each subtitle should not exceed 15 characters. "
                "When a punctuation mark is encountered, "
                "a new subtitle segment should be created. "
                f"original text:\n{ref_text}"
            )
        else:
            initial_prompt = (
                "Please output subtitles in simplified Simplified Chinese. \n"
                "Each subtitle should not exceed 15 characters. \n"
                "When a punctuation mark is encountered, "
                "a new subtitle segment should be created. \n"
                "每段字幕不要超过15个字。\n"
                "请自动在有标点符号的地方拆分输出。\n"
                "下面的内容是普通话的，请输出简体中文。\n"
            )
        # 处理当前片段
        result = model.transcribe(
            video_path,
            language="zh",
            task="transcribe",
            word_timestamps=True,
            initial_prompt=initial_prompt,
        )
        return result["segments"]
        # 生成 SRT 格式字幕
    finally:
        # 恢复原始函数
        whisper.audio.load_audio = original_load_audio
